package cn.edu.scau.dormitory_management_system.module.user.controller;

import java.io.IOException;
import java.util.UUID;

import cn.edu.scau.dormitory_management_system.config.session.MySessionContext;
import cn.edu.scau.dormitory_management_system.constant.Consts;
import cn.edu.scau.dormitory_management_system.entity.LoginLogEntity;
import cn.edu.scau.dormitory_management_system.entity.UserEntity;
import cn.edu.scau.dormitory_management_system.entity.UserRoleEntity;
import cn.edu.scau.dormitory_management_system.entity.dto.LogDTO;
import cn.edu.scau.dormitory_management_system.enums.UserStatusEnum;
import cn.edu.scau.dormitory_management_system.service.LoginLogService;
import cn.edu.scau.dormitory_management_system.module.user.service.UserService;
import cn.edu.scau.dormitory_management_system.service.UserRoleService;
import cn.edu.scau.dormitory_management_system.util.IPKit;
import cn.edu.scau.dormitory_management_system.util.MailUtils;
import cn.edu.scau.dormitory_management_system.util.StringUtils;
import cn.edu.scau.dormitory_management_system.util.TaleUtils;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 
 *
 * @author wanglingfu
 * @email 1006340605@qq.com
 * @date 2021-08-02 14:35:10
 */
@RestController
@RequestMapping("/user")
public class UserController extends BaseController{
    /**
     * 日志
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);

    @Autowired
    UserService userService;
    @Autowired
    UserRoleService userRoleService;

    /**
     * djc 8.4 + loginLog
     */
    @Autowired
    private LoginLogService logService;
    @Autowired
    private LogDTO cityDTO;

    @Autowired
    MailUtils mailUtils;
    /**
     * 用户登录
     * @param response
     * @param request
     * @param email
     * @param password
     * @param city djc 8.4 + loginLog
     * @return
     */
    @PostMapping("/login")
    public Object login(HttpServletResponse response, HttpServletRequest request,
                        @RequestParam("email") String email, @RequestParam("password") String password,
                        @RequestParam("city") String city, @RequestParam("uuid") String uuid,
                        @RequestParam("code") String code){
        JSONObject json = new JSONObject();
        String ip = IPKit.getIpAddrByRequest(request);
        LOGGER.info("用户IP地址"+ip);
        if (cache.get(uuid) == null || !cache.get(uuid).equals(code)){
            json.put(Consts.CODE,"0");
            json.put(Consts.MSG,"验证码错误");
            cache.del(uuid);
            return json;
        }
        cache.del(uuid);
        Integer error_count = cache.hget("login_error_count", ip);
        if (error_count != null && error_count >= 3){
            json.put(Consts.CODE,UserStatusEnum.ERROR_PASSWORD.getStatus());
            json.put(Consts.MSG,"您输入密码错误已经超过三次，请十分钟后再尝试");
            return json;
        }
        UserEntity userEntity = null;
        if (!TaleUtils.isEmail(email)){
            userEntity = userService.queryByUserName(email);
        }else {
            userEntity = userService.queryByEmail(email);
        }
        if (userEntity == null){
            json.put(Consts.CODE,UserStatusEnum.NOT_EXIST.getStatus());
            json.put(Consts.MSG,UserStatusEnum.NOT_EXIST.getDesc());
            return json;
        }else {
            if (userEntity.getPassword().equals(TaleUtils.MD5encode(password+userEntity.getEmail()))){
                json.put(Consts.CODE,UserStatusEnum.YES.getStatus());
                if (userEntity.getIsEnabled() == 1){
                    response.setHeader("token",request.getSession().getId());
                    json.put(Consts.MSG,UserStatusEnum.YES.getDesc());
                    json.put("token",request.getSession().getId());

                    cityDTO.setIp(ip); //djc 8.4 + loginLog
                    cityDTO.setCity(city); //djc 8.4 + loginLog
                    cityDTO.setUserName(userEntity.getUserName()); //djc 8.4 + loginLog

                    request.getSession().setAttribute("admin",userEntity);
                    UserEntity user = new UserEntity();
                    BeanUtils.copyProperties(userEntity,user);
                    user.setPassword("");
                    json.put("data",user);

                    //djc 8.4 + loginLog
                    LoginLogEntity logEntity = new LoginLogEntity();
                    logEntity.setUserName(userEntity.getUserName());
                    logEntity.setIpAddr(ip);
                    logEntity.setCity(city);
                    logEntity.setIsIn(0);
                    if(!StringUtils.isEmpty(city)) logService.insertLog(logEntity);
                }else {
                    json.put(Consts.CODE,3);
                    json.put(Consts.MSG,"未激活或被禁用");
                }
            }else {
                error_count = null == error_count ?1:error_count + 1;
                if (error_count < 3){
                    cache.hset("login_error_count",ip,error_count,10*60);
                    json.put(Consts.CODE,UserStatusEnum.ERROR_PASSWORD.getStatus());
                    json.put(Consts.MSG,UserStatusEnum.ERROR_PASSWORD.getDesc());
                }else {
                    cache.hset("login_error_count",ip,error_count,10*60);
                    json.put(Consts.CODE,UserStatusEnum.ERROR_PASSWORD.getStatus());
                    json.put(Consts.MSG,"您输入密码错误已经超过三次，请十分钟后再尝试");
                }
            }
        }
        return json;
    }

    /**
     * 异步判断密码
     * @param oldPassword
     * @param request
     * @return
     */
    @PostMapping("admin/judgePassword")
    public Object judgePassword (@RequestParam("oldPassword") String oldPassword,HttpServletRequest request){
        JSONObject json = new JSONObject();
        UserEntity admin = (UserEntity) request.getAttribute("admin");
        if (admin.getPassword().equals(TaleUtils.MD5encode(oldPassword+admin.getEmail()))){
            json.put(Consts.CODE,UserStatusEnum.YES_PASSWORD.getStatus());
            json.put(Consts.MSG,UserStatusEnum.YES_PASSWORD.getDesc());
        }else {
            json.put(Consts.CODE,UserStatusEnum.ERROR_PASSWORD.getStatus());
            json.put(Consts.MSG,UserStatusEnum.ERROR_PASSWORD.getDesc());
        }
        return json;
    }

    /**
     * 修改密码
     * @param newPassword
     * @param request
     * @return
     */
    @PostMapping("admin/updatePassword")
    public Object updatePassword(@RequestParam("newPassword") String newPassword,HttpServletRequest request){
        JSONObject json = new JSONObject();
        UserEntity userEntity = (UserEntity) request.getAttribute("admin");
        userEntity.setPassword(TaleUtils.MD5encode(newPassword+userEntity.getEmail()));
        boolean flag = userService.update(userEntity);
        if (flag){
            json.put(Consts.CODE, 1);
            json.put(Consts.MSG, "修改成功");
            request.getSession().setAttribute("admin",userEntity);
        }else {
            json.put(Consts.CODE, 0);
            json.put(Consts.MSG, "修改失败");
        }
        return json;
    }

    /**
     * 用户注册
     * @param request
     * @param user
     * @return
     */
    @PostMapping("/register")
    public Object register(HttpServletRequest request, @RequestBody UserEntity user) throws MessagingException {
        JSONObject json = new JSONObject();
        UserEntity userEntity = userService.queryByEmail(user.getEmail());
        if (userEntity == null){
            userEntity = userService.queryByUserName(user.getUserName());
            if (userEntity != null){
                json.put(Consts.CODE,0);
                json.put(Consts.MSG,"该学号已被注册");
                return json;
            }
            user.setIsEnabled(0);
            user.setRandomCode(UUID.randomUUID().toString().replace("-", ""));
            user.setPassword(TaleUtils.MD5encode(user.getPassword()+user.getEmail()));
            if (userService.insertUser(user)){
                mailUtils.sendActivateMail(user.getEmail(), user.getUserName(), user.getRandomCode());
                UserRoleEntity userRoleEntity = new UserRoleEntity().setRoleId(1).setUserId(user.getUserId());
                System.out.println(userRoleService.save(userRoleEntity));
                json.put(Consts.CODE,1);
                json.put(Consts.MSG,"注册成功,请激活账号");
            }else {
                json.put(Consts.CODE,0);
                json.put(Consts.MSG,"注册失败");
            }
        }else {
            if (userEntity.getIsEnabled() == 0){
                user.setIsEnabled(0);
                user.setRandomCode(UUID.randomUUID().toString().replace("-", ""));
                if (userService.update(user)){
                    mailUtils.sendActivateMail(user.getEmail(), user.getUserName(), user.getRandomCode());
                    json.put(Consts.CODE,1);
                    json.put(Consts.MSG,"注册成功");
                }else {
                    json.put(Consts.CODE,0);
                    json.put(Consts.MSG,"注册失败");
                }
            }else if (userEntity.getIsEnabled() == 1){
                json.put(Consts.CODE,0);
                json.put(Consts.MSG,"账号已激活");
            }else {
                json.put(Consts.CODE,0);
                json.put(Consts.MSG,"数据错误");
            }
        }
        return json;
    }
    @RequestMapping(value = "/admin/logout")
    public Object logout(HttpServletRequest request,HttpServletResponse response) throws IOException {
        //djc 8.10 + loginLog
        LoginLogEntity logEntity = new LoginLogEntity();
        logEntity.setUserName(cityDTO.getUserName());
        logEntity.setIpAddr(cityDTO.getIp());
        logEntity.setCity(cityDTO.getCity());
        logEntity.setIsIn(1);
        logService.insertLog(logEntity);

        JSONObject json = new JSONObject();
        //HttpSession session = (HttpSession) request.getAttribute("session");
        String tokenHeader = request.getHeader("token");
        HttpSession session = MySessionContext.getSession(tokenHeader);
        MySessionContext.delSession(session) ;
        //session.removeAttribute("admin");
        json.put("code", 0);
        json.put("msg", "ok");
//        response.sendRedirect("http://localhost:8001/login");
        return json;
    }
}
